package com.example.seleniumautotest.utils;

/*
* POI操作封装
* */

import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

@Component
@Slf4j
public class POIHandle {

    private XSSFWorkbook sheets;

    // 初始化
    public XSSFSheet init(String filePath, int sheetIndex){
        FileInputStream fileInputStream = null;
        try {
            fileInputStream = new FileInputStream(filePath);
        } catch (FileNotFoundException e) {
            log.info("文件地址错误：",e);
        }
        XSSFSheet sheetAt = null;
        try {
            sheets = new XSSFWorkbook(fileInputStream);
            sheetAt = sheets.getSheetAt(sheetIndex);
        } catch (IOException e) {
            log.info("文件IO异常：",e);
        }
        return sheetAt;
    }

    // 读取整行数据
    public XSSFRow getRow(XSSFSheet sheet, int rowIndex){
        return sheet.getRow(rowIndex);
    }

    // 读取单个数据
    public XSSFCell getCell(XSSFSheet sheet,int rowIndex,int cellIndex){
        return sheet.getRow(rowIndex).getCell(cellIndex);
    }

    // 写入数据
    public void setCell(XSSFSheet sheet,int rowIndex,int cellIndex,String value) throws IOException {
        sheet.getRow(rowIndex).getCell(cellIndex).setCellValue(value);
        // 文件流输出,优化项：执行过程中对执行结果进行记录，带执行完毕后对结果进行填充
    }

    // 获取总共行数
    public int getRowCount(XSSFSheet sheet){
        return sheet.getPhysicalNumberOfRows();
    }
}
